package sg.edu.nus.iss.billing.dao.bill;

import java.util.ArrayList;
import java.util.List;

import sg.edu.nus.iss.billing.common.DbUtil;
import sg.edu.nus.iss.billing.common.Util;
import sg.edu.nus.iss.billing.common.exception.BadDbCallException;
import sg.edu.nus.iss.billing.common.exception.InvalidParamsException;
import sg.edu.nus.iss.billing.vo.transaction.TransactionVO;

public class TransactionDAO implements ITransactionDAO {
	
	private ArrayList<String> data = null;
	private final static String FILE_PATH = "data//transaction.txt";
	
	public TransactionDAO(){
		try {
			data = (ArrayList<String>) DbUtil.loadDb(FILE_PATH);
		} catch (BadDbCallException e) {
			data = new ArrayList<String>();
			System.out.println(e.getMessage());
		}
	}
	
	private List<TransactionVO> getTransctn(String subscriptionId, String featureName) throws InvalidParamsException, InstantiationException, IllegalAccessException {
		ArrayList<TransactionVO> results = new ArrayList<TransactionVO>();
		for(int i=0;i<data.size();i++){ 
			TransactionVO transaction = new TransactionVO();
			transaction.setParameters(data.get(i));
			if (transaction.getSubscriptionId().equals(subscriptionId) 
					&& transaction.getFeatureName().equals(featureName)) {
					transaction = (TransactionVO) Util.getTransactionVOMap().get(featureName).newInstance();
					transaction.setParameters(data.get(i));
					results.add(transaction);
			}
		}
		return results;
	}
	
	public void createTransaction(TransactionVO transaction) throws BadDbCallException{
		data.add(transaction.serialised());
		DbUtil.saveDb(FILE_PATH, data);
	}

	@Override
	public List<TransactionVO> getTransactions(String subscriptionId,
			String featureName) {
		try {
			return getTransctn(subscriptionId, featureName);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvalidParamsException e) {
			e.printStackTrace();
		}
		return new ArrayList<TransactionVO>();
	}
}
